#!/usr/bin/env bash

# Generates new test credentials.
#
# The script must be executed from the repository root folder.
#
# Dependencies:
#   - gcloud
#   - jq

SECRET_JSON_PATH=test_credentials/secret.json
BIGQUERY_JSON_PATH=test_credentials/bigquery.json
BIGQUERY_JSON_ENC_PATH=test_credentials/bigquery.json.enc

# Generate a new key for dataform-testing service account and download it.
gcloud iam service-accounts keys create "${SECRET_JSON_PATH}" \
  --iam-account=dataform-testing@dataform-open-source.iam.gserviceaccount.com \
  --project=dataform-open-source

# Create bigquery.json for encryption. Basically we do the same thing
# as `dataform init-creds` will do but without creating dataform project.
cat <<EOF > "${BIGQUERY_JSON_PATH}"
{
    "projectId": "dataform-open-source",
    "credentials": $(jq -Rsa < ${SECRET_JSON_PATH}),
    "location": "US"
}
EOF

# Create encrypted secret
gcloud kms encrypt \
    --ciphertext-file="${BIGQUERY_JSON_ENC_PATH}" \
    --plaintext-file="${BIGQUERY_JSON_PATH}" \
    --project=dataform-open-source \
    --keyring=dataform-builder-keyring \
    --key=dataform-builder-key \
    --location=global

# Cleanup secrets
rm -f "${SECRET_JSON_PATH}"
rm -f "${BIGQUERY_JSON_PATH}"
